import React, { useEffect, useLayoutEffect, useState } from "react";
import TweenOne from "rc-tween-one";
import { Menu } from "antd";
import { getChildrenToRender } from "../utils";
import { Link, useLocation } from "react-router-dom";

const { Item, SubMenu } = Menu;
const Header = (props) => {
  const { dataSource } = props;
  const [selectMenuKey, setSelectMenuKey] = useState(["home"]);
  const navData = dataSource.Menu.children;
  const location = useLocation();

  const routerName = () => {
    console.log(location.pathname);
    let menu = location.pathname.split("/")?.[1];
    if (!menu) {
      menu = "home";
    }
    setSelectMenuKey([menu]);
  };
  useEffect(() => {
    routerName();
  }, []);
  const navChildren = navData.map((item) => {
    const { children: a, subItem, ...itemProps } = item;
    if (subItem) {
      return (
        <SubMenu
          key={item.name}
          {...itemProps}
          title={
            <div {...a} className={`header0-item-block ${a.className}`.trim()}>
              {a.children.map(getChildrenToRender)}
            </div>
          }
          popupClassName="header0-item-child"
        >
          {subItem.map(($item, ii) => {
            const { children: childItem } = $item;
            const child = childItem.href ? (
              <Link to={childItem.href}>
                {childItem.children.map(getChildrenToRender)}
              </Link>
            ) : (
              <div {...childItem}>
                {childItem.children.map(getChildrenToRender)}
              </div>
            );
            return (
              <Item key={$item.name || ii.toString()} {...$item}>
                {child}
              </Item>
            );
          })}
        </SubMenu>
      );
    }
    return (
      <Item key={item.name} {...itemProps}>
        <a {...a} className={`header0-item-block ${a.className}`.trim()}>
          {a.children.map(getChildrenToRender)}
        </a>
      </Item>
    );
  });

  return (
    <TweenOne
      component="header"
      animation={{ opacity: 0, type: "from" }}
      {...dataSource.wrapper}
      {...props}
    >
      <div {...dataSource.page} className={`${dataSource.page.className}`}>
        <TweenOne
          animation={{ x: -30, type: "from", ease: "easeOutQuad" }}
          {...dataSource.logo}
        >
          <img width="100%" src={dataSource.logo.children} alt="img" />
        </TweenOne>

        <Menu
          mode={"horizontal"}
          className="menu-wrap"
          selectedKeys={selectMenuKey}
          onClick={(val: any) => {
            console.log(val);
            setSelectMenuKey(val.key);
          }}
        >
          {navChildren}
        </Menu>
      </div>
    </TweenOne>
  );
};

export default Header;
